<template>
  <div class="keyboard-game">
    <!-- 背景音乐 -->
    <audio controls="true" autoplay="true" name="media" loop="true" hidden="true">
      <source src="../../../assets/audio/消灭外星人.mp3" type="audio/mpeg" />
    </audio>
    <Header :isTransBg="true" :isGoBack="false">
      <template v-slot:left>
        <span style="width:75px">消灭外星人</span>
      </template>
      <template v-slot:center>
        <div class="time">
          <span> 游戏时间：{{ watchTime | filterTime(0, "m") }} </span>
        </div>
        <div class="lightning-list">
          <span>体力：</span>
          <div class="lightning-item" v-for="index in lightnNum" :key="index">
            <img src="@/assets/img/icon-lightning.png" alt="" />
          </div>
          <div
            class="lightning-item lightning-item-gray"
            v-for="index in 5 - lightnNum"
            :key="'gray' + index"
          >
            <img src="@/assets/img/icon-lightning-gray.png" alt="" />
          </div>
        </div>
        <div class="difficulty ml10">
          <span> 当前难度：{{ difficultyObj[difficulty] }}</span>
        </div>
        <div class="difficulty ml10">
          <span> 当前积分：{{ total }}</span>
        </div>
      </template>
      <template v-slot:right>
        <div class="close-memeory" @click="goStudyIndex" style="z-index:2000">
          关闭
          <img class="ml5" src="@/assets/img/close-circle.png" alt="" />
        </div>
      </template>
    </Header>
    <CheckedDialog
      :wordNum="wordNum"
      @startGame="getChecked"
      @getPower="getPower"
      ref="checkedDialog"
    ></CheckedDialog>
    <div v-show="isShow">
      <span
        class="keyboard-game-list"
        :data-index="index < 3 ? index : ''"
        v-for="(item, index) of word"
        :key="index"
      >
        <div>
          <img src="../../../assets/img/keyboardItem.png" alt="" />
          <p>{{ item.list[0].paraphrase }}</p>
          <!-- <p>{{ item.word_name }}</p> -->
        </div>
      </span>
    </div>
    <!--  --><!--  -->
    <div class="right-write">
      <p>
        {{ input }}
      </p>
    </div>
  </div>
</template>

<script>
import {
  getWordNum,
  addEnergy,
  getGameWordList,
  decreaseEnergy,
  postGameResult,
} from "@/api/game.js";
import CheckedDialog from "./CheckedDialog";
export default {
  data() {
    return {
      input: "",
      isShow: false,
      lightnNum: 0, //体力
      wordData: [], // 数据
      word: [],
      wordTwo: [],
      wordNum: {
        totalNumber: 0, // 全部单词数量
        newWord: 0, //生词数量
        knowWord: 0, //熟词数量
        studyWord: 0, //
      },
      watchTime: 0, // 游戏时长
      gameTime: 0,
      total: 0, //积分
      chance: 3, //机会
      time: ["30", "29", "28", "27", "26", "25", "24"],
      difficulty: 0, //游戏难度
      timer: null,
      difficultyObj: {
        0: "入门",
        1: "简单",
        2: "中等",
        3: "困难",
        4: "专家",
        5: "大师",
        6: "特级大师",
      },
      num: 1,
      outWordNum: 0,
    };
  },
  created() {
    this.getWordNum();
    this.getGameWordList();
  },
  mounted() {
    //添加体力
    // this.addEnergy();
  },
  watch: {
    word() {},
    // 监听输入查看是否有正确答案
    input: {
      handler() {
        this.word.filter((item, index) => {
          if (item.word_name == this.input) {
            this.input = "";
            this.total += 100; // 加积分,一个单词100分
            this.outWordNum++; //消灭单词数
            this.word.splice(index, 1, this.wordTwo[0]);
            this.wordTwo.splice(0, 1);
            this.addWord(index);
            let diff = this.difficulty + 1; //游戏等级
            let word = (4 * (2 + diff) * diff) / 2;
            if (this.outWordNum == word) {
              console.log("jinjil晋级了");
              this.difficulty++;
              this.watchTime = this.time[this.difficulty];
            }
          }
        });
      },
    },
  },
  methods: {
    //开始游戏
    getChecked(data) {
      this.isShow = true;
      console.log(data);
      this.total = 0; // 重置积分
      this.chance = 3; // 重置机会
      this.watchTime = this.time[data.difficulty]; // 根据等级规定游戏时间
      this.gameTime = this.time[data.difficulty];
      this.difficulty = data.difficulty;
      if (this.lightnNum > 0) {
        this.decreaseEnergy(); //减体力
        this.startGame(); // 时间倒计时
        this.keyboardEvent(); //键盘事件
      } else {
        this.$alert("体力不足，请稍后再试哦~", "消息提示", {
          confirmButtonText: "确定",
          callback: () => {
            this.goStudyIndex();
          },
        });
      }
    },
    addWord(index) {
      // console.log("屏幕显示单词", this.word);
      // console.log("后备单词", this.wordTwo);
      let span = document.getElementsByClassName("keyboard-game-list")[index];
      // let arr = ["1", "2", "3", "4", "5", "6"];
      // let num = Math.floor(Math.random() * 6);
      if (this.num != undefined && span) {
        if (this.num < 7) {
          span.style.animation = `mymove${this.num} 15s linear 1`;
          this.num++;
        } else {
          span.style.animation = `mymove1 15s linear 1`;
          this.num = 2;
        }
      }
    },
    // 开始下落
    open() {
      this.input = "";
      console.log("开始下落");
      let span = document.getElementsByClassName(`keyboard-game-list`);
      for (let i = 0; i < 3; i++) {
        // 判断有没有该元素
        if (span[i] !== undefined) {
          span[i].style.animation = `mymove0 
          ${parseInt(Math.floor(Math.random() * 8) + 10)}s
           linear 1`;
        }
      }
      // 动画结束回调
      for (let i = 0; i < 3; i++) {
        // 判断有没有该元素
        if (span[i] !== undefined) {
          span[i].addEventListener("animationend", (e) => {
            this.chance--; //三次失误的机会,触底一次减一
            console.log(this.chance);
            if (this.chance <= 0) {
              clearInterval(this.timer);
              this.$refs.checkedDialog.openDialog();
              this.removeKeyboardEvent(); // 关闭键盘事件
              this.postGameResult(0);
              return;
            }
            console.log("动画结束了...");

            this.word.filter((item, index) => {
              // 查找到掉落的单词
              if (item.list[0].paraphrase == e.target.innerText) {
                //替换掉落的单词
                this.word.splice(index, 1, this.wordTwo[0]);
                this.wordTwo.splice(0, 1);
                this.addWord(i);
              }
            });
            console.log(this.word);
          });
        }
      }
    },
    // 游戏时间倒计时
    startGame() {
      this.open(); //开始游戏
      this.timer = setInterval(() => {
        this.watchTime--;
        if (this.watchTime <= 0) {
          clearInterval(this.timer);
          let openTimer = setTimeout(() => {
            this.$refs.checkedDialog.openDialog();
            this.removeKeyboardEvent();
            this.postGameResult(1);
            clearInterval(openTimer);
          }, 500);
          // 游戏结束
        }
      }, 1000);
    },
    //提交每一小局的游戏结果
    postGameResult(isTrue) {
      this.isShow = false;
      let params = {
        testTime: this.gameTime, // 游戏用时
        grade: this.total, // 最后得分
        isTrue, // 是否完成
        id: this.wordData.id, // 主键id
        classify: 2, //游戏分类
      };
      console.log(params);
      postGameResult(params).then((res) => {
        if (res.code == 200) {
          console.log("提交成功", res.data);
        }
      });
    },
    // 获取单词
    getGameWordList() {
      /** type 题型 * number 返回题目个数 */
      let params = { type: 4, number: 120 };
      getGameWordList(params).then((res) => {
        if (res.code === 200 && res.data && res.data.game_volist) {
          this.wordData = res.data;
          this.wordTwo = res.data.game_volist;
          for (let i = 0; i < 2; i++) {
            this.word.push(this.wordData.game_volist[0]);
            this.wordTwo.splice(0, 1);
          }
          this.gameTime = this.wordData.game_time;
          // this.canvas();
        }
      });
    },
    getPower() {
      this.getWordNum();
      // this.$bus.$emit("power", this.lightnNum);
    },
    // 获取当前体力
    getWordNum() {
      getWordNum().then((res) => {
        if (res.code === 200 && res.data) {
          this.wordNum.totalNumber = res.data.wordNumber;
          this.wordNum.newWord = res.data.a2;
          this.wordNum.knowWord = res.data.a1;
          this.wordNum.studyWord = res.data.a1 + res.data.a2;
          this.lightnNum = res.data.energy;
          this.$bus.$emit("power", this.lightnNum);
        }
      });
    },
    //减体力
    decreaseEnergy() {
      decreaseEnergy().then((res) => {
        if (res.code == 200) {
          this.getWordNum();
        }
      });
    },
    // 添加键盘按下事件
    keyboardEvent() {
      document.body.addEventListener("keydown", this.keyboardDown);
    },
    // 移除键盘事件
    removeKeyboardEvent() {
      this.input = "";
      this.difficulty = 0;
      this.outWordNum = 0;
      // 清空数组内的单词
      this.word = [];
      this.$nextTick(() => {
        // 准备好下一句的单词
        for (let i = 0; i < 2; i++) {
          this.word.push(this.wordData.game_volist[0]);
          this.wordTwo.splice(0, 1);
        }
      });
      document.body.removeEventListener("keydown", this.keyboardDown);
    },
    keyboardDown(e) {
      let englishLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ. ";
      if (englishLetters.indexOf(e.key) == "-1") {
        // Backspace
        if (e.key == "Backspace") {
          this.input = this.input.substring(0, this.input.length - 1);
        }
        // 空格键
        if (e.key == " ") {
          this.input += " ";
        }
      } else {
        this.input += e.key;
      }
    },
    // 添加体力
    addEnergy() {
      addEnergy().then((res) => {
        if (res.code === 200) {
          this.getWordNum();
        }
      });
    },
    //退出游戏
    goStudyIndex() {
      this.$router.push({
        name: "studyIndex",
      });
    },
  },
  components: { CheckedDialog },
};
</script>

<style scoped></style>
